<?php

namespace Common\Model;

use Think\Model;

/**
 * 用户消息模型
 */
class MsgModel extends Model {

    const NORMAL = 0;   // 消息状态：未阅读
    const DELTEL = -1;  // 消息状态：已阅读

    /**
     * 向Msg表中新增一条记录
     * @param $data
     * @return mixed
     */
    public static function addData($data){
        if ($result = M('Msg')->add($data)) {
            UserCountModel::update($data['gid'], 'msg');
        }
        return $result;
    }

    /**
     * 向Msg表中同时新增多条数据
     * @param $data
     * @return mixed
     */
    public static function addDatas($data){
        if ($result = M('Msg')->addAll($data)) {
            foreach ($data as $v) {
                UserCountModel::update($v['gid'], 'msg');
            }
        }
        return $result;
    }

    /**
     * 获取用户的所有消息
     * @param $uid
     * @param $p
     * @param $pcount
     * @return array
     */
    public static function getMsgs($uid, $p, $pcount){
        $count = M('Msg')->where(['gid' => $uid])->count();
        $list = $count ? M()->table(['wo_msg' => 'm', 'wo_user' => 'u'])->where(['m.gid' => $uid])->where('m.sid = u.id')->field('m.*,u.nick')->order('m.status = '.self::NORMAL.' desc,m.`create` desc')->page($p.','.$pcount)->select() : [];
        return [
            'count' => $count,
            'list' => $list
        ];
    }

    /**
     * 更新消息数据的状态
     * @param $uid
     * @param $mid
     * @param $data
     * @return bool
     */
    public static function update($uid, $mid, $data){
        $where = [
            'id' => $mid,
            'gid' => $uid,
            'status' => self::NORMAL
        ];
        if($result = M('Msg')->where($where)->save($data)){
            UserCountModel::update($uid, 'msg', false);
        }
        return $result;
    }

    /**
     * 删除指定消息
     * @param $uid
     * @param $mid
     * @param $status
     * @return bool
     */
    public static function deleteMsg($uid, $mid, $status){
        $where = [
            'id' => $mid,
            'gid' => $uid,
            'status' => $status
        ];
        $result = M('Msg')->where($where)->delete();
        if ($result && $status == self::NORMAL) {
            UserCountModel::update($uid, 'msg', false);
        }
        return $result;
    }

}